<template>
  <!-- 默认选择全部 报告单元  -->
  <div id="selectWtAll">
    <el-popover popper-class="popoverSelectWt" :popper-style="{zIndex:9999999}" :tabindex="999000" placement="bottom-start" width="400" trigger="click" :teleported="true" :visible="popoverVisible">
      <el-scrollbar style="height: 240px; max-height: 500px">
        <div class="popoverTreeParent" v-for="groupItem in groupedData" :key="groupItem">
          <div class="popoverTreeItem">
            <el-icon>
              <!-- 向下实心箭头 -->
              <CaretBottom></CaretBottom>
            </el-icon>
            <!-- 工作组 树形大类 -->
            {{ groupItem }}
          </div>
          <div class="popoverBox">
            <el-radio-group v-model="selectedRadioId">
              <template v-for="(option, index) in groupedRadioData" :key="index">
                <div v-for="(item, itemIndex) in option" :key="itemIndex">
                  <el-radio v-if="item.dictName === groupItem" style="padding: 5px; margin: 5px 10px 10px 0" border :key="item.id" @change="repSelectChange(item)" :label="item.id">{{item.rptGroup}} - {{ item.rptGroupName }}</el-radio>
                </div>
              </template>
            </el-radio-group>
          </div>
        </div>
      </el-scrollbar>

      <template #reference>
        <el-input placeholder="请选择工作组" v-model="selectedName" @click="handleInputClick" ref="inputRef" :style="{ width: props.inputWidth }" @blur="inputBlur" :clearable="isClear" @clear="resetSelectedVal">
        </el-input>
      </template>
    </el-popover>
  </div>
</template>

<script lang="ts" setup>
// 引入组件区 ==========
import { reactive, ref, getCurrentInstance, onMounted, watch } from 'vue';
let { proxy }: any = getCurrentInstance();
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import { AppStore } from '../../../../stores/store';
import { isEmpty } from 'lodash';
import { LocPost } from '@/utils/LocRequestHelper';

// 全局变量定义区 ==========
let store = AppStore();
let rptGroupList = store.userInfo.rptGroupList;
let selectedRadioId = ref(''); //当前选中的id
let selectedName = ref(''); //当前选择的名字
let workGroup = ref(''); //当前选择的名字
let workGroupName = ref(''); //当前选择的名字
let rptGroupOptions: any = reactive([]); //当前用户权限可用的
let groupedData: any = reactive([]); // 创建一个空对象，用于存储按照workGroup分类后的分类名
let groupedRadioData: any = reactive({}); //筛选当前匹配名字下的radio
let inputRef: any = ref(null); // 引用el-input元素
let popoverVisible = ref(false); // 控制popover的显示状态
import Axios from '@/api';
import { IsEmpty } from '@/utils/common';

let props = defineProps({
  url: String,
  inputWidth: { type: String, default: '200px' }, //输入框长度
  isClear: { type: Boolean, default: false }, //清除小叉号
  isShowAll: { type: Boolean, default: true } //工作组是否默认选择全部（即默认工作组id为null）
});

let url = props.url; // url地址

//#region  自定义指令
// 自定义指令
const removeAriaHidden: ObjectDirective<HTMLElement> = {
  mounted(el) {
    const ariaEls = el.querySelectorAll('.el-radio__original');
    ariaEls.forEach((item) => {
      item.removeAttribute('aria-hidden');
    });
  }
};

// 使用自定义指令
proxy.$.directives = { removeAriaHidden: removeAriaHidden };
//#endregion

defineExpose({
  resetSelectedVal
});

// 监听父组件传过来的URL
watch(
  () => props.url,
  (newval, oldval) => {
    url = newval;
  },
  {
    deep: true,
    immediate: true
  }
);

// 方法定义区 =============
onMounted(() => {
  if (props.isShowAll) {
    findRptGroupOptions(); // 获取下拉选项选中的第一个数据
    return;
  }
});

//   选中一条后关闭popover
function inputBlur() {
  popoverVisible.value = false; // 关闭popover
}

let pc = null;
// 获取下拉选项全部数据
function findRptGroupOptions() {
  proxy.$http
    .get(url)
    .then(async (res: any) => {
      let ii = IsEmpty(rptGroupList) ? res.data : res.data.filter((item: any) => rptGroupList.includes(item.id));
      rptGroupOptions.push(...ii);
      // 遍历每个数据项，按照workGroup进行分类
      rptGroupOptions.forEach((item: any) => {
        const workGroup = item.dictName;
        // 检查groupedData是否包含当前的workGroup
        if (!groupedData.includes(workGroup)) {
          // 如果不包含，则将workGroup添加到groupedData中
          groupedData.push(workGroup);
        }
      });
      // 遍历groupedData，将每个分组的数据提取出来，并合并成一个数组
      groupedRadioData = groupedData.map((group: any) => {
        return rptGroupOptions.filter((option: any) => option.dictName === group);
      });

      // 本地缓存中的报告单元
      let localWorkGroupIngo = store.locWorkGroup;
      if (!isEmpty(localWorkGroupIngo.rptGroup)) {
        selectedRadioId.value = localWorkGroupIngo.rptGroup;
        workGroup.value = localWorkGroupIngo.workGroup;
        workGroupName.value = localWorkGroupIngo.dictName;
        selectedName.value = `${localWorkGroupIngo.rptGroup}-${localWorkGroupIngo.rptGroupName}`;
        proxy.$emit('fatherMethod', selectedRadioId, selectedName,workGroup,workGroupName);
      } else {
        /**本地默认报告单元 */
        //如果是本地参数 则查出当前页面的计算机名称
        if (isEmpty(pc)) {
          try {
            pc = await LocPost((window as any).apiUrl.VUE_APP_LOCAL_PRINT_URL + '/api/LocalParams/get-local-pc-name', {});
            let localComputerName = isString(pc) ? pc : '';
            Axios.get(`/api/sys/sysParamValue/findSysParamFieldAndValueByCode`, {
              params: { paramCode: 'bdxtcs', localComputer: localComputerName }
            })
              .then((res: any) => {
                if (res && res.status && res.status.code && res.status.code === 1) {
                  const objlist = res.data;
                  if (!isEmpty(objlist)) {
                    const a = objlist.filter((p: any) => p.field === 'localDefaultRptGroup');
                    if (a && a.length > 0 && a[0] && !isEmpty(a[0].value)) {
                      const idx = rptGroupOptions.findIndex((p) => p.id === a[0].value);
                      if (idx > -1) {
                        selectedRadioId.value = rptGroupOptions[idx].rptGroup;
                        selectedName.value = rptGroupOptions[idx].rptGroupName;
                        workGroup.value = rptGroupOptions[idx].workGroup;
                        workGroupName.value = rptGroupOptions[idx].dictName;
                      } else {
                        selectedRadioId.value = ''; //默认选中全部
                        selectedName.value = '全部'; //默认显示全部字样
                      }
                    } else {
                      selectedRadioId.value = ''; //默认选中全部
                      selectedName.value = '全部'; //默认显示全部字样
                    }
                  } else {
                    selectedRadioId.value = ''; //默认选中全部
                    selectedName.value = '全部'; //默认显示全部字样
                  }
                } else {
                  selectedRadioId.value = ''; //默认选中全部
                  selectedName.value = '全部'; //默认显示全部字样
                }
                proxy.$emit('fatherMethod', selectedRadioId, selectedName,workGroup,workGroupName);

              })
              .catch((err) => {
                selectedRadioId.value = ''; //默认选中全部
                selectedName.value = '全部'; //默认显示全部字样
                workGroup.value = ''; //默认显示全部字样
                workGroupName.value = '';
                proxy.$emit('fatherMethod', selectedRadioId, selectedName,workGroup,workGroupName);
              });
          } catch (error) {
            selectedRadioId.value = ''; //默认选中全部
            selectedName.value = '全部'; //默认显示全部字样
            workGroup.value = ''; //默认显示全部字样
            workGroupName.value = '';
            proxy.$emit('fatherMethod', selectedRadioId, selectedName,workGroup,workGroupName);
          }
        }
      }

      //proxy.$emit('fatherMethod', selectedRadioId, selectedName);
    })
    .catch((err: any) => {
      VxeMessage('获取数据异常', VxeNotifyType.error);
    });
}
/**判断是否是字符串 */
function isString(value: unknown): value is string {
  return typeof value === 'string';
}
// 点击input 让popover展开
function handleInputClick() {
  popoverVisible.value = true; // 点击input时显示popover
}

// // 点击单选框 切换
function repSelectChange(value: any) {
  selectedRadioId.value = value.rptGroup;
  selectedName.value = value.rptGroupName;
  workGroup.value = value.workGroup;
  workGroupName.value = value.dictName;
  proxy.$emit('fatherMethod', selectedRadioId, selectedName,workGroup,workGroupName);
  popoverVisible.value = false; // 关闭popover
  inputRef.value?.blur(); // 关闭popover后让input失去焦点
}

// 置空所选的id和name
function resetSelectedVal() {
  //   当点击清除按钮后
  if (!props.isClear) {
    return;
  }
  popoverVisible.value = true;
  selectedRadioId.value = '';
  selectedName.value = props.isShowAll ? '全部' : '';
  proxy.$emit('fatherMethod', {
    id: null,
    name: '',
    level: 0,
    parent: {}
  });
}
</script>

<style lang="scss" scoped>
#selectWtAll {
  // margin-right: 10px;
  .popoverBox {
    margin-top: 5px;
  }
}
:deep(.el-radio__label) {
  line-height: 24px;
}
</style>
